package com.example.projects;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.Facebook;

public class Comment extends CPT3004Menu {

	// Instance of Facebook Class
	private Facebook fb;
	private SharedPreferences mPrefs;
	private OnSharedPreferenceChangeListener prefListener;

	// UI elements
	private EditText editText;
	private RatingBar ratingBar;
	private Button submit;
	private Button clear;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
        // create a listener for login/logout events
        mPrefs = getSharedPreferences("", Context.MODE_PRIVATE);
        prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        	  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        		  // check if token set and update UI
        		  if(prefs.getString("access_token", null) != null) {
        			  // logged in
        			  loginUpdateUI();
        		  }else {
        			  // logged out
        			  logoutUpdateUI();
        		  }
        		  
        	  }
        };
        mPrefs.registerOnSharedPreferenceChangeListener(prefListener);

    	setContentView(R.layout.comment);
    	
    	// get facebook
        fb = ((CPT3004)getApplication()).getFacebook();
    	if(fb == null) {
    		// create new facebook
    		fb = new Facebook(((CPT3004)getApplication()).getAppID());
    		
    		// prepare facebook for use
        	String access_token = mPrefs.getString("access_token", null);
        	long expires = mPrefs.getLong("access_expires", 0);
        	
        	// reuse old token if possible
        	if (access_token != null) {
    	    	fb.setAccessToken(access_token);
	        	if(expires != 0) {
	        		fb.setAccessExpires(expires);
	        	}
	        	fb.extendAccessTokenIfNeeded(this, null);
        	}
    		// store facebook
    		((CPT3004)getApplication()).setFacebook(fb);
    	}
    	
    	// initialise UI elements
    	editText = (EditText) findViewById(R.id.edit_comment);
    	ratingBar = (RatingBar) findViewById(R.id.ratingBar);
    	submit = (Button)findViewById(R.id.confirm);
    	clear = (Button)findViewById(R.id.clear);

    	// button displays submit if user logged in or login if not
    	if(fb.isSessionValid()) {
    		loginUpdateUI();
    	}else{
    		logoutUpdateUI();
    	}
    	
    	String LS = System.getProperty("line.separator");
		String str2 = "";
		String facebooknamestr = "";
		String reviewstr = "";
		String ratingstr = "";
		try {
			str2 = readFile(getFilesDir().getAbsolutePath());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			JSONArray json_array = new JSONArray(str2);
			LinearLayout tl = (LinearLayout)findViewById(R.id.comlinlayout);
			
			for(int i = 0; i < json_array.length()-1; i++){
				//TableRow tr = new TableRow(getApplicationContext());
				JSONObject json_data = (JSONObject) json_array.get(i);
				facebooknamestr = json_data.getString("Name");
				reviewstr = json_data.getString("Review");
				ratingstr = json_data.getString("Rating");
				
				TextView fbname = new TextView(this);
				fbname.setText(facebooknamestr);
				fbname.setTypeface(Typeface.DEFAULT_BOLD);
				//\n Rating: "+ratingstr+LS);
				fbname.setTextSize(20);
			
				TextView review = new TextView(this);
				review.setText(reviewstr+LS);
				review.setTextSize(20);
				
				RatingBar rating = new RatingBar(this, null, android.R.attr.ratingBarStyleSmall);
				rating.setRating(Float.parseFloat(ratingstr));
				rating.setNumStars(5);
				rating.setIsIndicator(true);
				rating.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
				
				tl.addView(fbname);
				tl.addView(rating);
				tl.addView(review);
				
				//tl.addView(tr);
				
			}
		} catch (JSONException e) {
			e.printStackTrace();
			
		}
		
		
		
        //Read JSON file
        
		String str = "";
		String imagestr = "";
		try {
			str = readImage();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("before JSON");
		System.out.println(str);
		try {
    		JSONObject json_data = new JSONObject(str);
    		imagestr = json_data.getString("Image");

		} catch (JSONException e) {
			
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			Toast.makeText(this, "No product data exists.", Toast.LENGTH_SHORT).show();
		}

		
		
        // get image if necessary otherwise use the old one
	    ImageView image = (ImageView) findViewById(R.id.commentimage);
	    getImage gi = new getImage(this, image);
	    gi.execute(imagestr);
    }
    
    public void refresh(View view){
    	Intent intent = this.getIntent();
    	String barcode = intent.getStringExtra(Main.BARCODE);
    	AccessDatabase ad = new AccessDatabase(this);
    	ad.execute(barcode, getFilesDir().getAbsolutePath(), "comment");
    	
    }
    
    public void confirmComment(View view){
    	Facebook fb = ((CPT3004)getApplication()).getFacebook();
    	MyFacebook.setUsernameID((CPT3004)getApplication());
    	if (fb.isSessionValid()) {
	    	// get username and id
	    	String name = ((CPT3004)getApplication()).getFBName();
	    	String id = ((CPT3004)getApplication()).getFBID();
	    	// send comment to database
			//get barcode
			Intent intent = getIntent();
	    	String barcode = intent.getStringExtra(Main.BARCODE);
	    	//get edit box text
	        EditText editText = (EditText) findViewById(R.id.edit_comment);
	        String message = editText.getText().toString();
	        //get rating bar value
	    	RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
	    	float ratefloat = ratingBar.getRating();
	    	int rateint = (int) ratefloat;
	    	String ratestring = Integer.toString(rateint);
	        //Call function and send to database
	        UpdateCommentDatabase ucd = new UpdateCommentDatabase(this);
	        ucd.execute(barcode, message, ratestring, id, name, getFilesDir().getAbsolutePath());
    	}
    }
    
	private String readImage() throws FileNotFoundException, IOException {

		Intent intent = this.getIntent();
		String message = intent.getStringExtra(Main.BARCODE);
		FileInputStream stream = new FileInputStream(new File(this.getFilesDir().getAbsolutePath()+"/" + message + "product.json"));
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		String str = Charset.defaultCharset().decode(bb).toString();
		stream.close();
		System.out.println("readFile: "+str);
		return str;
	}
    
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
			fb.authorizeCallback(requestCode, resultCode, data);
	}
    
	private String readFile(String path) throws FileNotFoundException, IOException {
		Intent intent = getIntent();
		String message = intent.getStringExtra(Main.BARCODE);
		FileInputStream stream = new FileInputStream(new File(path+"/" + message + "comment.json"));
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		String str = Charset.defaultCharset().decode(bb).toString();
		stream.close();
		return str;
	}
    
    //The control of clear button and clear the comment of the edit box
    public void clearComment(View view){
    	EditText editText = (EditText) findViewById(R.id.edit_comment);
    	//set edit box text to empty string
    	editText.setText("");
    }
    
    private void logoutUpdateUI() {
    	editText.setVisibility(View.GONE);
    	ratingBar.setVisibility(View.GONE);
    	submit.setVisibility(View.GONE);
    	clear.setVisibility(View.GONE);
    }
    
    private void loginUpdateUI() {
    	editText.setVisibility(View.VISIBLE);
    	ratingBar.setVisibility(View.VISIBLE);
    	submit.setVisibility(View.VISIBLE);
    	clear.setVisibility(View.VISIBLE);
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	mPrefs.unregisterOnSharedPreferenceChangeListener(prefListener);
    }

}